package com.longcai.service.impl.homegood;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longcai.bean.ApiResult;
import com.longcai.constants.BaseConstants;
import com.longcai.entity.homegood.ClyjGoodsHomepage;
import com.longcai.entity.homegood.ClyjGoodsPics;
import com.longcai.entity.homegood.ClyjGoodsSpec;
import com.longcai.entity.homepage.ClyjGoodsType;
import com.longcai.mapper.homegood.ClyjGoodsHomepageMapper;
import com.longcai.mapper.homegood.ClyjGoodsSpecMapper;
import com.longcai.mapper.homepage.ClyjGoodsPicsMapper;
import com.longcai.mapper.homepage.ClyjGoodsTypeMapper;
import com.longcai.service.homegood.ClyjGoodsHomepageService;
import com.longcai.util.Page;
import com.longcai.util.SolrConnect;
import com.longcai.util.TwoDimensionCode;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 * 首页商品表 服务实现类
 * </p>
 *
 * @author LWK
 * @since 2019-03-22
 */
@Service
public class ClyjGoodsHomepageServiceImpl extends ServiceImpl<ClyjGoodsHomepageMapper, ClyjGoodsHomepage> implements ClyjGoodsHomepageService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ClyjGoodsHomepageMapper clyjGoodsHomepageMapper;

    @Autowired
    private ClyjGoodsTypeMapper clyjGoodsTypeMapper;
    @Autowired
    private ClyjGoodsSpecMapper clyjGoodsSpecMapper;
    @Autowired
    private ClyjGoodsPicsMapper clyjGoodsPicsMapper;

    /**
     * 商品存入solr
     *
     * @return
     */
    @Override
    public ApiResult saveGoodSolr() {

        QueryWrapper<ClyjGoodsHomepage> queryWrapper = new QueryWrapper<>();
        List<ClyjGoodsHomepage> list = clyjGoodsHomepageMapper.selectList(queryWrapper);
        boolean b = SolrConnect.insertSolr(list);
        if (b) {
            return ApiResult.success(b);
        } else {
            return ApiResult.fail(b);
        }
    }


    /**
     * 通过类型查询商品
     *
     * @param type
     * @return
     */
    @Override
    public ApiResult getGoodsBytype(String type) {
        List list = new ArrayList();
        Map map = new HashMap();
        try {
            QueryWrapper<ClyjGoodsType> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type_id", type);
            List<ClyjGoodsType> clyjGoodsTypes = this.clyjGoodsTypeMapper.selectList(queryWrapper);
            for (ClyjGoodsType clyjGoodsType : clyjGoodsTypes) {
                list.add(clyjGoodsType.getGoodsId());
            }
            map.put("list", list);
            List<ClyjGoodsHomepage> clyjGoodsHomepages = this.clyjGoodsHomepageMapper.getgoodslist(map);
            logger.debug("查询成功++++++++++", clyjGoodsHomepages);
            return ApiResult.success(clyjGoodsHomepages);
        } catch (Exception e) {
            logger.error("查询失败");
            e.printStackTrace();
            return ApiResult.fail("查询失败"+e.getMessage());
        }
    }


    /**
     * 通过品牌从solr查询商品
     *
     * @param brand
     * @return
     */
    @Override
    public Page<ClyjGoodsHomepage> getGoodsBybrand(String brand) {
        try {
            QueryWrapper<ClyjGoodsHomepage> queryWrapper = new QueryWrapper<>();
            //查询solr里的商品数据
            Page<ClyjGoodsHomepage> page = new Page<ClyjGoodsHomepage>();
            page.setPageNo(Integer.valueOf(0));
            if (StringUtils.isNotEmpty(brand) && !brand.equals("")) {
                return SolrConnect.getAll("goodsBrandId:" + brand, page);
            }
        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();
        }
        return null;
    }


    /**
     * 查询商品详情
     *
     * @param goodsid
     * @return
     */
    @Override
    public Map<String, Object> getGoods(String goodsid) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        QueryWrapper<ClyjGoodsSpec> queryWrapper = new QueryWrapper<>();
        try {
            //查询商品数据
            ClyjGoodsHomepage selectById = clyjGoodsHomepageMapper.selectById(goodsid);
            resultMap.put("goodsData", selectById);
            //查询商品规格以及轮播图
            queryWrapper.eq("goods_id", goodsid);
            List<ClyjGoodsSpec> specList = clyjGoodsSpecMapper.selectList(queryWrapper);
            //构造规格数据
            List<Map<String, Object>> specLists = new ArrayList<Map<String, Object>>();
            String goodsSpec = selectById.getGoodsSpec();
            if (goodsSpec == null || goodsSpec.equals(""))
                return resultMap;
            String[] specNames = goodsSpec.split(",");
            for (int i = 0; i < specNames.length; i++) {
                Map<String, Object> specMap = new HashMap<String, Object>();
                Set<String> sets = new HashSet<String>();
                for (ClyjGoodsSpec clyjGoodsSpec : specList) {
                    String specDetail = clyjGoodsSpec.getSpecDetail();
                    if (specDetail == null || specDetail.equals(""))
                        continue;
                    sets.add(specDetail.split(",")[i]);
                }
                specMap.put("name", specNames[i]);
                specMap.put("value", sets);
                specMap.put("flag", specNames.length - i);
                specLists.add(specMap);
            }
            resultMap.put("specList", specLists);
        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();
        }
        return resultMap;
    }


    @Override
    public Map<String, Object> getSpec(JSONObject params) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String goodsid = params.getString("goodsid");    //商品id
        String flag = params.getString("flag");            //规格标识
        String spec = params.getString("spec");            //规格名称
        //根据商品id和规格名称查询规格列表
        try {
            QueryWrapper<ClyjGoodsSpec> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("goods_id", goodsid);
            queryWrapper.like("spec_detail", spec);
            //查询商品详细信息
            ClyjGoodsHomepage selectById = clyjGoodsHomepageMapper.selectById(goodsid);
            //查询规格列表
            List<ClyjGoodsSpec> specList = clyjGoodsSpecMapper.selectList(queryWrapper);
            List<Map<String, Object>> specLists = new ArrayList<Map<String, Object>>();
            String goodsSpec = selectById.getGoodsSpec();
            if (goodsSpec == null || goodsSpec.equals("") || specList == null || specList.size() == 0)
                return resultMap;
            if (flag != null && Integer.valueOf(flag) == 2) {    //如果选择的为倒数第二级
                String[] specNames = selectById.getGoodsSpec().split(",");
                Map<String, Object> specMap = new HashMap<String, Object>();
                List<String> sets = new ArrayList<String>();
                List<Integer> sets2 = new ArrayList<Integer>();
                for (ClyjGoodsSpec clyjGoodsSpec : specList) {
                    String specDetail = clyjGoodsSpec.getSpecDetail();
                    if (specDetail == null || specDetail.equals(""))
                        continue;
                    sets.add(specDetail.split(",")[specNames.length - 1]);
                    sets2.add(clyjGoodsSpec.getSpecNum());
                }
                specMap.put("name", specNames[specNames.length - 1]);
                specMap.put("value", sets);
                specMap.put("flag", 1);
                specMap.put("num", sets2);
                specLists.add(specMap);
            } else if (flag != null && Integer.valueOf(flag) == 1) {
                //获取轮播图
                QueryWrapper<ClyjGoodsPics> w = new QueryWrapper<ClyjGoodsPics>();
                String specId = specList.get(0).getSpecId();
                w.eq("spec_id", specId);
                w.eq("goods_id", goodsid);
                List<ClyjGoodsPics> selectList = clyjGoodsPicsMapper.selectList(w);
                resultMap.put("picData", selectList);
            } else {
                String[] specNames = goodsSpec.split(",");
                for (int i = 1; i < specNames.length; i++) {
                    Map<String, Object> specMap = new HashMap<String, Object>();
                    Set<String> sets = new HashSet<String>();
                    for (ClyjGoodsSpec clyjGoodsSpec : specList) {
                        String specDetail = clyjGoodsSpec.getSpecDetail();
                        if (specDetail == null || specDetail.equals(""))
                            continue;
                        sets.add(specDetail.split(",")[i]);
                    }
                    specMap.put("name", specNames[i]);
                    specMap.put("value", sets);
                    specMap.put("flag", specNames.length - i);
                    specLists.add(specMap);
                }
            }
            resultMap.put("data", specLists);
        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();
        }
        return resultMap;
    }


    @Override
    public ApiResult<?> shareGoodsQRcode(JSONObject params) throws UnsupportedEncodingException {
        //商品id
        String goodsid = params.getString("goodsid");
        if (StringUtils.isEmpty(goodsid)) {
            return ApiResult.fail("商品Id不能为空");
        }
        //分享商品的用户id
        String shareGoodsUserId = "hyf";
        //分享商品的--（商品详情的路径）
        String shareGoodsUrl = BaseConstants.DOMAIN_NAME + "/clyjGoodsHomepage/getGoods";
        //生成二维码
        // 生成扫描地址
        StringBuilder qrcodeScannerUrl = new StringBuilder();
        {
            qrcodeScannerUrl.append(URLEncoder.encode(shareGoodsUrl, "UTF-8"));
            qrcodeScannerUrl.append("?");
            qrcodeScannerUrl.append("goodsid=" + goodsid);
            qrcodeScannerUrl.append("&shareGoodsUserId=" + shareGoodsUserId);
        }
        //String localUrl = BaseConstants.IMG_SERVER + "/";//图片服务器的域名47.105.145.14
     // 用户主目录
        String localUrl = System.getProperties().getProperty("user.home");
        System.out.println(localUrl);
        // 文件名
        StringBuilder userOfUrl = new StringBuilder("home/");
        userOfUrl.append("qrcode/");
        userOfUrl.append("goodsid"+goodsid + "/");
        userOfUrl.append("shareGoodsUserId"+shareGoodsUserId + "/");
        userOfUrl.append(System.currentTimeMillis() + "/");
        new File(localUrl + userOfUrl).mkdirs();    // 创建文件夹
        long targetUrlLength = qrcodeScannerUrl.toString().getBytes("UTF-8").length;
        int qrcodeSize = 0;
        // 控制生成的二维码大小
        if (targetUrlLength <= 120) {         // 7
            qrcodeSize = 7;
        } else if (targetUrlLength <= 410) {    // 15
            qrcodeSize = 15;
        } else {
            qrcodeSize = 20;        // 这里最大20已经能满足需要了,最大可以设置为40
        }
        TwoDimensionCode.encoderQRCode(
                qrcodeScannerUrl.toString(),
                localUrl + userOfUrl,
                "png",
                qrcodeSize);
        Map<String, String> map = new HashMap<>();
        map.put("shareGoodsUrl", localUrl + userOfUrl);
        System.out.println(map.get("shareGoodsUrl"));
        return ApiResult.success(map);
    }
}
